const router = require('koa-router')()
// let fs = require( "fs");
// let path = require( "path");
const child_process = require('child_process')
const kill =  require('tree-kill')
const serverIp = "192.168.50.98"
let handleList = {}
let rtspList = {}

router.post('/start', async (ctx, next) => {
  console.log(ctx.request)
  let body = ctx.request.body
  if (body.url) {
    if (rtspList[body.url]) {
      rtspList[body.url].num += 1
      ctx.body = { message: rtspList[body.url].rtmp, t: rtspList[body.url].t}
      ctx.status = 200
      return
    }
    let t = new Date().getTime()
    let rtmp = `rtmp://${serverIp}:1935/hls/${t}`
    console.log(rtmp)
    let handle = child_process.exec(`ffmpeg -i ${body.url} -f flv -r 25 -s 1080*720 -an ${rtmp}`, { cwd: __dirname })

    handleList[t] = body.url
    rtspList[body.url] = {
      num: 1,
      t, handle, rtmp,
      lastTime: t
    }
    handle.stdout.on('data', (data) => {
      console.log('info', data)
    })
  
    handle.stderr.on('data', (data) => {
      // console.log(t + ' warn:', data)
    })

    ctx.body = { message: rtmp, t}
    ctx.status = 200
  } else {
    ctx.throw(500, { message: 'url不能为空！' })
  }


})

router.post('/stop', async (ctx, next) => {

  let data = ctx.request.body
  if (data.t && handleList[data.t]) {
    let url = handleList[data.t]
    rtspList[url].num -= 1
    if (rtspList[url].num === 0) {
      kill(rtspList[url].handle.pid)
      delete handleList[data.t]
      delete rtspList[url]
    }
    ctx.body = { message: '关闭成功！' }
    ctx.status = 200
    
  } else {
    ctx.throw(500, { message: 'error' })
  }

})

// heartbeat

router.post('/heartbeat', async (ctx, next) => {

  let data = ctx.request.body
  if (data.url && rtspList[data.url]) {
    rtspList[data.url].lastTime = new Date().getTime()
    ctx.body = { message: 'heartbeat!' }
    ctx.status = 200
  } else {
    ctx.throw(500, { message: 'error' })
  }
  
})

const getOpenLog = () => {
  console.log('--------------------------------------openLog-------------------------------------')
  for (const key in rtspList) {
    if (rtspList.hasOwnProperty(key)) {
      const item = rtspList[key];
      console.log(`${key}---${item.num}`)
    }
  }
  console.log('---------------------------------------End---------------------------------------')
}


let nowTime = ''
setInterval(() => {
  nowTime = new Date().getTime()
  for (const key in rtspList) {
    if (rtspList.hasOwnProperty(key)) {
      const item = rtspList[key];
      if (nowTime - item.lastTime > 0.5 * 60 * 1000) {
        kill(item.handle.pid)
        delete handleList[item.t]
        delete rtspList[key]
      }
    }
  }
  getOpenLog()
}, 0.5 * 60 * 1000);



module.exports = router